package cn.founder.basic.cntroller;

import cn.founder.basic.util.AjaxResult;
import cn.founder.basic.util.FastDfsUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    //上传接口
    @PostMapping
    public AjaxResult upload(@RequestPart("file") MultipartFile file){
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //截取 后缀名
            String exName = filename.substring(filename.lastIndexOf(".") + 1);
            //截取 文件地址
            String path = FastDfsUtil.upload(file.getBytes(), exName);
            //将上传成功后的文件地址 发送给前端  前端使用回调函数接收
            return new AjaxResult().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("上传文件失败");
        }
    }


    //删除接口
    @DeleteMapping
    public AjaxResult delete(@RequestParam("path") String path){
        try {
            String substringpath = path.substring(1);//   group1/M00/01/4B/rBE3kWFL9qeAC6V3AADFLXNXgyc455.jpg
            String group = substringpath.substring(0, substringpath.indexOf("/"));
            String fileName = substringpath.substring(substringpath.indexOf("/")+1);
            FastDfsUtil.delete(group, fileName);
            return AjaxResult.myself();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("删除失败！");
        }
    }
}
